﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQ.Receive
{
    class Program
    {
        private static readonly ConnectionFactory rabbitFactory = new ConnectionFactory()
        {
            HostName = "localhost",
            UserName = "guest",
            Password = "guest",
            Port = 5672
        };
        /// <summary>
        /// 路由名称
        /// </summary>
        const string ExchangeName = "ExchangeName";
        /// <summary>
        /// 对列名称
        /// </summary>
        const string QueueName = "QueueName";

        static void Main(string[] args)
        {
            Console.InputEncoding = Encoding.Unicode;
            Console.OutputEncoding = Encoding.Unicode;
            DirectAcceptExchange();

            Console.WriteLine("输入任意值退出程序！");
            Console.ReadLine();
        }

        private static void DirectAcceptExchange()
        {
            using (IConnection connection = rabbitFactory.CreateConnection())
            {
                using (IModel channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
                    //声明队列
                    channel.QueueDeclare(QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueBind(QueueName, ExchangeName, routingKey: QueueName);

                    while (true)
                    {
                        BasicGetResult msgResponse = channel.BasicGet(QueueName, autoAck: false);
                        if (msgResponse != null)
                        {
                            var msgBody = Encoding.UTF8.GetString(msgResponse.Body);
                            Console.WriteLine(string.Format("接收时间：{0}，消息内容：{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msgBody));
                        }
                    }
                }
            }
        }
    }
}
